package com.wayz.service;

import com.wayz.entity.dto.agent.AgentDto;
import com.wayz.entity.pojo.agent.DAgentUser;
import com.wayz.entity.redis.agent.RAgentUser;
import com.wayz.exception.WayzException;
import com.wayz.mapper.DAgentUserDAO;
import com.wayz.redis.BeanIdKeyEnum;
import com.wayz.redis.RedisUtils;
import com.wayz.util.FileMD5Helper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;

import javax.annotation.Resource;

/**
 * 代理商用户服务实现类
 *
 * @author mike.ma@wayz.ai
 */
@org.springframework.stereotype.Service("agentUserService")
@Service(version = "1.0.0", protocol = "dubbo")
@RefreshScope
public class AgentUserServiceImpl implements AgentUserService {

    /**
     * Redis工具类
     */
    @Resource(name = "redisUtils")
    private RedisUtils redisUtils;

    /**
     * 代理商用户
     */
    @Resource(name = "dAgentUserDAO")
    private DAgentUserDAO dAgentUserDAO;

    /**
     * 创建代理商用户
     *
     * @param myId
     * @param agentId
     * @param roleId
     * @param dto
     * @return
     * @throws WayzException
     */
    @Override
    public Long createUser(Long myId, Long agentId, Long roleId, AgentDto dto) throws WayzException {
        // 校验用户名是否存在 手机号
        Boolean exist = dAgentUserDAO.existByPhone(dto.getTelephone());
        if (exist) {
            throw new WayzException("用户手机号已存在");
        }
        // 用户ID 创建用户
        Long userId = redisUtils.incrBy(BeanIdKeyEnum.PROXY_USER_SAAS.getKey(), RedisUtils.STEP_SIZE);
        DAgentUser create = new DAgentUser();
        create.setId(userId);
        create.setRoleId(roleId);
        create.setAgentId(agentId);
        create.setCreatorId(myId);
        create.setUsername(dto.getTelephone());
        create.setPassword(FileMD5Helper.getMD5String("123456"));
        create.setName(dto.getProxyType() == 1 ? dto.getContacts() : dto.getName());
        create.setPhone(dto.getTelephone());
        dAgentUserDAO.create(userId, create);

        // 设置缓存
        this.cacheAgentUser(create);
        return userId;
    }


    /**
     * 代理商重置密码
     *
     * @param id          代理商ID
     * @param newPassword 新的密码
     * @throws WayzException
     */
    @Override
    public void resetAgentUserPassword(Long myId, Long id, String newPassword) throws WayzException {
        DAgentUser byAgentId = dAgentUserDAO.getByAgentId(id);
        if (byAgentId == null) {
            throw new WayzException("账户异常");
        }
        dAgentUserDAO.updatePassword(id, newPassword);
    }

    /**
     * 存入缓存
     *
     * @param create
     */
    public void cacheAgentUser(DAgentUser create) throws WayzException {
        RAgentUser rUser = new RAgentUser();
        rUser.setUserId(create.getId());
        BeanUtils.copyProperties(create, rUser);
        redisUtils.hPutBeanAsHash(RAgentUser.getKey(create.getId()), rUser);
    }
}
